package com.yjht.online.generate.impl.org;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.yjht.online.arg.ArgParam;
import com.yjht.online.generate.Generate;
import com.yjht.online.generate.GlobalContext;
import com.yjht.online.generate.impl.org.plat.kd.CorpGenerateProccessorKd;
import com.yjht.online.generate.impl.org.plat.kd.OrgGenerateProccesorKd;
import com.yjht.online.generate.impl.org.plat.wkd.CorpGenerateProcessorWkd;
import com.yjht.online.generate.impl.org.plat.wkd.OrgGenerateProccesorWKd;
import com.yjht.online.generate.model.org.CorpInfo;
import com.yjht.online.generate.model.org.LrdOrg;
import com.yjht.online.generate.model.org.OrgInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 生成机构相关
 */
public class OrgGenerate implements Generate {
    final static Logger logger = LoggerFactory.getLogger(OrgGenerate.class);

    @Override
    public void generate(ArgParam argParam) {
        if (StrUtil.isBlank(argParam.getOrgFilePath())) {
            return;
        }

        File file = new File(argParam.getOrgFilePath());
        if(!file.exists()){
            return;
        }
        InputStream inputStream = null;
        try {
             inputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            logger.error("机构信息表不存在");
        }
        List<OrgInfo> result = null;
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        try {
            result = ExcelImportUtil.importExcel(inputStream, OrgInfo.class, params);
        } catch (Exception exception) {
            logger.error("机构信息Excel读取失败"+exception.getMessage());
        }
        if(result == null){
            throw new RuntimeException("机构读取失败");
        }
        result = result
                .stream()
                .filter(f->StrUtil.isNotBlank(f.getIndex()) && StrUtil.isNotBlank(f.getOrgCd()) )
                .collect(Collectors.toList());

        List<LrdOrg> lrdOrgs = toLrdOrd(result);
        CorpInfo corpInfo = toCorpInfo(result);

        //全局变量
        GlobalContext.setOrgInfos(result);
        GlobalContext.setCorpInfo(corpInfo);
        GlobalContext.setLrdOrgs(lrdOrgs);

        OrgGenerateProccesorKd orgGenerateProccesorKd = new OrgGenerateProccesorKd();
        OrgGenerateProccesorWKd orgGenerateProccesorWkd = new OrgGenerateProccesorWKd();
        CorpGenerateProccessorKd corpGenerateProccessorKd = new CorpGenerateProccessorKd();
        CorpGenerateProcessorWkd corpGenerateProcessorWkd = new CorpGenerateProcessorWkd();

        logger.info("生成机构相关数据");
        //快贷机构
        orgGenerateProccesorKd.generateOrgInfo(lrdOrgs);
        //微快贷机构
        orgGenerateProccesorWkd.generateOrgInfo(lrdOrgs);
        //快贷法人
        corpGenerateProccessorKd.generateCorpCd(corpInfo);
        //微快贷法人
        corpGenerateProcessorWkd.generateCorpCd(corpInfo);
        logger.info("机构相关数据完成");
    }

    private  List<LrdOrg> toLrdOrd(List<OrgInfo> orgInfos) {
        List<LrdOrg> lrdOrgs = new ArrayList<>();
        for (OrgInfo orgInfo : orgInfos) {
            LrdOrg lrdOrg = new LrdOrg();
            lrdOrg.setCorpCd(orgInfo.getCorpCd());
            lrdOrg.setOrgCd(orgInfo.getOrgCd());
            lrdOrg.setOrgName(orgInfo.getOrgName());

            if (orgInfo.getOrgCd().equals(orgInfo.getCorpCd())) {
                lrdOrg.setOrgPcd("1");
            } else {
                lrdOrg.setOrgPcd(orgInfo.getCorpCd());
            }
            lrdOrg.setOrgRelaType("00");
            lrdOrg.setOrgFlag("0");
            lrdOrg.setOrgVflag("0");
            lrdOrg.setCrtDate(DateUtil.format(new Date(),"YYYY/MM/dd"));
            lrdOrg.setMtnDate(DateUtil.format(new Date(),"YYYY/MM/dd"));
            lrdOrg.setOrgAbb("");
            lrdOrg.setWdId("");
            lrdOrg.setLevelid("");
            lrdOrg.setOrgDesc("");
            lrdOrg.setOrgType("");
            lrdOrg.setWorkingTimeMorning("8:30-12:00");
            lrdOrg.setWorkingTimeNoon("13:00-17:30");

            lrdOrgs.add(lrdOrg);
        }
        return lrdOrgs;
    }

    private CorpInfo toCorpInfo(List<OrgInfo> orgGenerates){

        if(CollectionUtil.isEmpty(orgGenerates)){
            throw new RuntimeException("解析机构失败");
        }

        Optional<OrgInfo> orgInfoOption = orgGenerates.stream()
                .filter(f -> StrUtil.isNotBlank(f.getCorpCd()) && StrUtil.isNotBlank(f.getOrgCd()))
                .filter(f -> f.getCorpCd().equals(f.getOrgCd()))
                .findFirst();

        OrgInfo orgInfo  = orgInfoOption.orElseThrow(()-> new RuntimeException("找不到法人信息"));

        CorpInfo corpInfo = new CorpInfo();
        corpInfo.setCorpCd(orgInfo.getCorpCd());
        corpInfo.setCorpFlag("0");
        corpInfo.setCorpName(orgInfo.getOrgName());
        corpInfo.setCrtDate(DateUtil.format(new Date(),"YYYY-MM-dd"));
        corpInfo.setMtnDate(DateUtil.format(new Date(),"YYYY-MM-dd"));
        corpInfo.setHost("");
        return corpInfo;
    }
}
